#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        int m = board.size(), n = board[0].size();

        int dx[8] = { -1, -1, -1, 0, 0, 1, 1, 1 };
        int dy[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };

        function<int(int, int)>
            check = [&](int r, int c)
            {
                int ret = 0;
                for (int i = 0; i < 8; i++)
                {
                    int x = r + dx[i];
                    int y = c + dy[i];
                    if (x >= 0 && y >= 0 && x < m && y < n && (board[x][y] == 'M' || board[x][y] == 'X'))
                    {
                        ret++;
                    }
                }
                return ret;
            };

        function<void(int, int)>
            dfs = [&](int r, int c)
            {
                if (board[r][c] != 'E') return;

                int i = check(r, c);
                if (i) board[r][c] = i + '0';
                else
                {
                    board[r][c] = 'B';
                    for (int i = 0; i < 8; i++)
                    {
                        int x = r + dx[i];
                        int y = c + dy[i];
                        if (x >= 0 && y >= 0 && x < m && y < n)
                        {
                            dfs(x, y);
                        }
                    }
                }
            };

        int r = click[0], c = click[1];
        if (board[r][c] == 'M')
        {
            board[r][c] = 'X';
        }
        else if (board[r][c] == 'E')
        {
            dfs(r, c);
        }

        return board;
    }
};